package xdu.lz.stage4_atomic.chapter1_atomicInteger;

import java.util.concurrent.atomic.AtomicInteger;

/**
 *JDK1.7以及以下有自旋锁【乐观锁】，JDK1.8直接没有了。分析自旋锁
 */
public class AtomicIntegerTest{

    // thread-safe
    // private static volatile int value = 0;
    private static AtomicInteger value = new AtomicInteger(0);


    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                while (true){
                    // value ++ 不是原子操作 ，会出现线程安全问题。 value++ :  read value,set value+1 ,write value
//                    System.out.println(Thread.currentThread().getName() + " : "+ (value++));

                    System.out.println(Thread.currentThread().getName() + " : "+ value.getAndIncrement());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
